<template>
  <div class="shopTimes">
    <!-- 页面主体 -->
    <g-main>
      <div class="shopTimes-wrapper">
        <!-- 店铺数据总览 -->
        <div class="store-summary">
          <div class="summary-title clearfix">
            <div class="name">
              <span class="pageName">逛店频率</span>
              <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                <i class="iconfont">&#xe72d;</i>
                <div slot="content">
                  日逛店次数：指某一个自然日顾客来店次数
                  <br>
                  <br>
                  周逛店次数：指某一周（周一至周日）顾客来店次数
                  <br>
                  <br>
                  月逛店次数：指某一个自然月顾客来店次数
                </div>
              </el-tooltip>
            </div>
          </div>
          <el-row class="summary-main clearfix">
            <el-col :span="8" style="margin-right:20px;">
              <el-date-picker v-model="mainDate"
                              align="right"
                              type="date"
                              placeholder="选择日期"
                              size="mini"
                              :clearable="false"
                              value-format="yyyy-MM-dd"
                              @change="changeMainDay(mainDate)"
                              :picker-options="pickerOptionsOfMain">
              </el-date-picker>
            </el-col>
          </el-row>
        </div>
        <div class="box">
          <div class="charts">
            <div class="charts-title">
              <span class="chartsTitle">日逛店次数分布</span>
            </div>
            <div class="dayPicker">
              <el-date-picker v-model="dayOfValue"
                              align="right"
                              type="date"
                              placeholder="多日对比，请选择日期"
                              size="mini"
                              :clearable="false"
                              @change="changeDay(dayOfValue)"
                              value-format="yyyy-MM-dd"
                              :picker-options="pickerOptionsOfDay">
              </el-date-picker>
            </div>
            <div class="seletedArray">
              <el-tag v-for="tag in daytags"
                      :key="tag.name"
                      closable
                      @close="handleCloseOfDay(tag)"
                      style="margin-left:10px;margin-bottom:10px;"
                      :type="tag.type">
                      {{tag.name}}
              </el-tag>
            </div>
            <div class="panel-charts">
              <customer-number-echart :options="timesOfDailyChartsOption"></customer-number-echart>
            </div>
            <div class="tableWrapper" ref="Day" style="overflow:hidden;height:0px;">
              <div class="tablelist" ref="tableOfDay">
                <div class="panel-title">
                  <span>日逛店次数分布明细</span>
                  <span class="save-csv-link" @click="SaveDateToDesktop('day')">
                    <i class="iconfont">&#xe68e;</i>
                    导出CSV</span>
                </div>
                <div class="panel-table">
                  <el-table :data="currTableDataOfDay"
                            border
                            size="small"
                            highlight-current-row
                            style="width: 100%">
                    <el-table-column prop="goShoppingTines"
                                     label="逛店次数"
                                     align="center"
                                     sortable
                                     width="180">
                    </el-table-column>
                    <el-table-column prop="customerNumber"
                                     align="center"
                                     sortable
                                     label="顾客数">
                      <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                    </el-table-column>
                    <el-table-column prop="customerNumberRadio"
                                     align="center"
                                     sortable
                                     label="顾客数占比">
                      <template slot-scope="scope">{{ scope.row.customerNumberRadio !== null && scope.row.customerNumberRadio !== undefined ? scope.row.customerNumberRadio : '0' }}</template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
            <div class="table">
              <span class="trigger" @click="showTable('Day')">{{this.showDayTable ? '收起数据明细' : '展开数据明细'}}</span>
            </div>
          </div>
        </div>
        <div class="box">
          <div class="charts">
            <div class="charts-title">
              <span class="chartsTitle">周逛店次数分布</span>
            </div>
            <div class="dayPicker">
              <el-date-picker v-model="weekOfValue"
                              type="week"
                              size="mini"
                              format="yyyy 第 WW 周"
                              :picker-options="pickerOptionsOfWeek"
                              :clearable="false"
                              @change="changeWeek(weekOfValue)"
                              placeholder="多周对比，请选择周">
              </el-date-picker>
            </div>
            <div class="seletedArray">
              <el-tag v-for="tag in weektags"
                      :key="tag.name"
                      closable
                      @close="handleCloseOfWeek(tag)"
                      style="margin-left:10px;margin-bottom:10px;"
                      :type="tag.type">
                      {{tag.name}}
              </el-tag>
            </div>
            <div class="panel-charts">
              <customer-number-echart :options="timesOfWeeklyChartsOption"></customer-number-echart>
            </div>
            <div class="tableWrapper" ref="Week" style="overflow:hidden;height:0px;">
              <div class="tablelist" ref="tableOfWeek">
                <div class="panel-title">
                  <span>周逛店次数分布明细</span>
                  <span class="save-csv-link" @click="SaveDateToDesktop('week')">
                    <i class="iconfont">&#xe68e;</i>
                    导出CSV</span>
                </div>
                <div class="panel-table">
                  <el-table :data="currTableDataOfWeek"
                            border
                            size="small"
                            highlight-current-row
                            style="width: 100%">
                    <el-table-column prop="goShoppingTines"
                                     label="逛店次数"
                                     align="left"
                                     sortable
                                     :sort-method="sortPercentConvMethods"
                                     width="180">
                    </el-table-column>
                    <el-table-column prop="customerNumber"
                                     align="left"
                                     sortable
                                     label="顾客数">
                      <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                    </el-table-column>
                    <el-table-column prop="customerNumberRadio"
                                     align="left"
                                     sortable
                                     label="顾客数占比">
                      <template slot-scope="scope">{{ scope.row.customerNumberRadio !== null && scope.row.customerNumberRadio !== undefined ? scope.row.customerNumberRadio : '0' }}</template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
            <div class="table">
              <span class="trigger" @click="showTable('Week')">{{this.showWeekTable ? '收起数据明细' : '展开数据明细'}}</span>
            </div>
          </div>
        </div>
        <div class="box">
          <div class="charts">
            <div class="charts-title">
              <span class="chartsTitle">月逛店次数分布</span>
            </div>
            <div class="dayPicker">
              <el-date-picker v-model="monthOfValue"
                              type="month"
                              size="mini"
                              :picker-options="pickerOptionsOfMonth"
                              :clearable="false"
                              @change="changeMonth(monthOfValue)"
                              value-format="yyyy-MM"
                              placeholder="多月对比，请选择月">
              </el-date-picker>
            </div>
            <div class="seletedArray">
              <el-tag v-for="tag in monthtags"
                      :key="tag.name"
                      closable
                      @close="handleCloseOfMonth(tag)"
                      style="margin-left:10px;margin-bottom:10px;"
                      :type="tag.type">
                      {{tag.name}}
              </el-tag>
            </div>
            <div class="panel-charts">
              <customer-number-echart :options="timesOfMonthlyChartsOption"></customer-number-echart>
            </div>
            <div class="tableWrapper" ref="Month" style="overflow:hidden;height:0px;">
              <div class="tablelist" ref="tableOfMonth">
                <div class="panel-title">
                  <span>月逛店次数分布明细</span>
                  <span class="save-csv-link" @click="SaveDateToDesktop('month')">
                    <i class="iconfont">&#xe68e;</i>
                    导出CSV</span>
                </div>
                <div class="panel-table">
                  <el-table :data="currTableDataOfMonth"
                            border
                            size="small"
                            highlight-current-row
                            style="width: 100%">
                    <el-table-column prop="goShoppingTines"
                                     label="逛店次数"
                                     align="center"
                                     sortable
                                     :sort-method="sortPercentConvMethods"
                                     width="180">
                    </el-table-column>
                    <el-table-column prop="customerNumber"
                                     align="center"
                                     sortable
                                     label="顾客数">
                      <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                    </el-table-column>
                    <el-table-column prop="customerNumberRadio"
                                     align="center"
                                     sortable
                                     label="顾客数占比">
                      <template slot-scope="scope">{{ scope.row.customerNumberRadio !== null && scope.row.customerNumberRadio !== undefined ? scope.row.customerNumberRadio : '0' }}</template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              </div>
            <div class="table">
              <span class="trigger" @click="showTable('Month')">{{this.showMonthTable ? '收起数据明细' : '展开数据明细'}}</span>
            </div>
          </div>
        </div>
      </div>
    </g-main>
  </div>
</template>
<script type="text/ecmascript-6">
// components
import Main from '@/components/main'
import customerEchart from '@/components/echarts'
// element-ui
import { Row, Col, DatePicker, Tooltip, Tabs, TabPane, Table, TableColumn, Tag } from 'element-ui'
import Moment from 'moment'

import { mapGetters } from 'vuex'
// api
import Config from '@/utils/config.js'
// 单天图表配置============================
import customerNumberEchartInitOption from './customerNumberEchartInitOption.js'

// API =========================
import { APIGetFrequencyOfDailyData, APIGetFrequencyOfWeeklyData, APIGetFrequencyOfMonthlyData } from '@/api/trajectory.js'

export default {
  name: 'shoptimes',

  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elDatePicker: DatePicker,
    elTooltip: Tooltip,
    elTabs: Tabs,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    elTag: Tag,
    // countUP component
    // 项目自定义组件
    gMain: Main,
    customerNumberEchart: customerEchart,
    customerTimesEchart: customerEchart,
    customerAnalyzeEchart: customerEchart,
    areaCustomerFlowEchart: customerEchart,
    customerAreaDataEchart: customerEchart
  },

  created () {
    this.APIGetFrequencyOfDailyData(this.mainDate)
    this.APIGetFrequencyOfWeeklyData(this.mainDate)
    this.APIGetFrequencyOfMonthlyData(this.mainDate)
  },

  mounted () {
  },

  updated () {
    this.heightOfDayTable = this.$refs.tableOfDay.offsetHeight
    this.heightOfWeekTable = this.$refs.tableOfDay.offsetHeight
    this.heightOfMonthTable = this.$refs.tableOfDay.offsetHeight
  },

  beforeDestroy () {
  },

  data () {
    return {
      heightOfDayTable: null,
      heightOfWeekTable: null,
      heightOfMonthTable: null,
      showDayTable: false,
      showWeekTable: false,
      showMonthTable: false,
      mainDate: Moment().subtract(1, 'day').format('YYYY-MM-DD'),
      pickerOptionsOfMain: {
        disabledDate (time) {
          return time.getTime() > Moment().subtract(1, 'day')
        }
      },
      dayOfValue: null,
      daytags: [{
        name: Moment().subtract(1, 'day').format('YYYY-MM-DD'),
        type: 'info'
      }],
      weekOfValue: null,
      weektags: [{
        name: Moment().subtract(Number(Moment().format('E')) + 6, 'day').format('YYYY.MM.DD') + '-' + Moment().subtract(Number(Moment().format('E')), 'day').format('YYYY.MM.DD'),
        type: 'info'
      }],
      monthOfValue: null,
      monthtags: [{
        name: Moment().subtract(1, 'month').format('YYYY-MM'),
        type: 'info'
      }],
      // default tab name
      activeTabsName: 'customerNumberView',
      // 客流人数相关
      timesOfDailyChartsOption: customerNumberEchartInitOption,
      timesOfWeeklyChartsOption: customerNumberEchartInitOption,
      timesOfMonthlyChartsOption: customerNumberEchartInitOption,
      customerTimesEchartOption: null,
      // 图表数据
      frequencyOfDailyData: {},
      dailydata: null,
      frequencyOfWeeklyData: {},
      weeklyData: null,
      frequencyOfMonthlyData: {},
      monthlyData: null
    }
  },

  computed: {
    ...mapGetters([
      'mallId',
      'token'
    ]),
    pickerOptionsOfDay () {
      const disabledDate = (time) => {
        return time.getTime() > Moment().subtract(1, 'day')
      }
      const shortcuts = [
        {
          text: '上周同期',
          onClick: (picker) => {
            const date = Moment(this.mainDate).subtract(7, 'day').format('YYYY-MM-DD')
            picker.$emit('pick', date)
          }
        },
        {
          text: '上月同期',
          onClick: (picker) => {
            const date = Moment(this.mainDate).subtract(28, 'day').format('YYYY-MM-DD')
            picker.$emit('pick', date)
          }
        }
      ]
      return {
        disabledDate,
        shortcuts
      }
    },
    pickerOptionsOfWeek () {
      const disabledDate = (time) => {
        let weekOfday = Moment().format('E')
        return time.getTime() > Moment().subtract(weekOfday, 'day')
      }
      const firstDayOfWeek = 1
      const shortcuts = [
        {
          text: '上周同期',
          onClick: (picker) => {
            const startOfCurrweek = Moment().subtract(Number(Moment().format('E')) - 1, 'day').format('YYYY-MM-DD')
            const chooseWeek = Moment(this.mainDate).format('YYYY-MM-DD')
            let weekOfday = Number(Moment(this.mainDate).format('E'))
            let date = null
            if (Moment(chooseWeek).isBefore(startOfCurrweek)) {
              date = Moment(this.mainDate).subtract(weekOfday, 'day').toDate()
            } else {
              date = Moment(this.mainDate).subtract(weekOfday + 7, 'day').toDate()
            }
            picker.$emit('pick', date)
          }
        },
        {
          text: '上月同期',
          onClick: (picker) => {
            const startOfCurrweek = Moment().subtract(Number(Moment().format('E')) - 1, 'day').format('YYYY-MM-DD')
            const chooseWeek = Moment(this.mainDate).format('YYYY-MM-DD')
            let weekOfday = Number(Moment(this.mainDate).format('E'))
            let date = null
            if (Moment(chooseWeek).isBefore(startOfCurrweek)) {
              date = Moment(this.mainDate).subtract(weekOfday + 14, 'day').toDate()
            } else {
              date = Moment(this.mainDate).subtract(weekOfday + 21, 'day').toDate()
            }
            picker.$emit('pick', date)
          }
        }
      ]
      return {
        disabledDate,
        firstDayOfWeek,
        shortcuts
      }
    },
    pickerOptionsOfMonth () {
      const disabledDate = (time) => {
        return time.getTime() > Moment().subtract(1, 'month')
      }
      const shortcuts = [
        {
          text: '上月同期',
          onClick: (picker) => {
            let date = null
            if (Moment(this.mainDate).format('YYYY-MM') === Moment().format('YYYY-MM')) {
              date = Moment(this.mainDate).subtract(2, 'month').format('YYYY-MM')
            } else {
              date = Moment(this.mainDate).subtract(1, 'month').format('YYYY-MM')
            }
            picker.$emit('pick', date)
          }
        }
      ]
      return {
        disabledDate,
        shortcuts
      }
    },
    currTableDataOfDay () {
      const data = []
      const shopingsTimesDataOfDay = this.dailydata || []
      for (let key in shopingsTimesDataOfDay) {
        let stats = shopingsTimesDataOfDay[key]
        let item = {}
        item.goShoppingTines = stats ? stats.times : null
        item.customerNumber = stats ? stats.customer_num : null
        item.customerNumberRadio = stats ? stats.ratio : null
        data.push(item)
      }
      return data
    },
    currTableDataOfWeek () {
      const data = []
      const shopingsTimesDataOfWeek = this.weeklyData || []
      for (let key in shopingsTimesDataOfWeek) {
        let stats = shopingsTimesDataOfWeek[key]
        let item = {}
        item.goShoppingTines = stats ? stats.times : null
        item.customerNumber = stats ? stats.customer_num : null
        item.customerNumberRadio = stats ? stats.ratio : null
        data.push(item)
      }
      return data
    },
    currTableDataOfMonth () {
      const data = []
      const shopingsTimesDataOfMonth = this.monthlyData || []
      for (let key in shopingsTimesDataOfMonth) {
        let stats = shopingsTimesDataOfMonth[key]
        let item = {}
        item.goShoppingTines = stats ? stats.times : null
        item.customerNumber = stats ? stats.customer_num : null
        item.customerNumberRadio = stats ? stats.ratio : null
        data.push(item)
      }
      return data
    }
  },
  watch: {
    daytags () {
      let dayArr = this.daytags.map(item => item.name)
      const base = {
        type: 'bar',
        barMaxWidth: '20%'
      }
      const dailydata = this.frequencyOfDailyData || {}
      let data = []
      for (let key in dailydata) {
        if (dayArr.includes(key)) {
          let item = {}
          item.name = key
          item.data = dailydata[key].map(item => Number(item.ratio.split('%')[0]).toFixed(2))
          data.push(Object.assign(item, base))
        }
      }
      this.timesOfDailyChartsOption.series = data
    },
    weektags () {
      let weekArr = this.weektags.map(item => item.name)
      const base = {
        type: 'bar',
        barMaxWidth: '20%'
      }
      const weeklydata = this.frequencyOfWeeklyData || {}
      let data = []
      for (let key in weeklydata) {
        if (weekArr.includes(key)) {
          let item = {}
          item.name = key
          item.data = weeklydata[key].map(item => Number(item.ratio.split('%')[0]).toFixed(2))
          data.push(Object.assign(item, base))
        }
      }
      this.timesOfWeeklyChartsOption.series = data
    },
    monthtags () {
      let monthArr = this.monthtags.map(item => item.name)
      const base = {
        type: 'bar',
        barMaxWidth: '20%'
      }
      const monthlydata = this.frequencyOfMonthlyData || {}
      let data = []
      for (let key in monthlydata) {
        if (monthArr.includes(key)) {
          let item = {}
          item.name = key
          item.data = monthlydata[key].map(item => Number(item.ratio.split('%')[0]).toFixed(2))
          data.push(Object.assign(item, base))
        }
      }
      this.timesOfMonthlyChartsOption.series = data
    }
  },

  methods: {
    // 日期选择器变化
    changeMainDay (value) {
      this.daytags = []
      this.weektags = []
      this.monthtags = []
      this.dayOfValue = null
      this.weekOfValue = null
      this.monthOfValue = null
      APIGetFrequencyOfDailyData({ shop: this.mallId, date: value })
        .then((res) => {
          this.dailydata = res.data.stats
          this.frequencyOfDailyData[value] = res.data.stats
          this.daytags.push({ name: value, type: 'info' })
        })
      const currMonth = Moment().format('YYYY-MM')
      const chooseMonth = Moment(value).format('YYYY-MM')
      let [month, range] = ['', '']
      if (currMonth === chooseMonth) {
        month = Moment(value).subtract(1, 'month').format('YYYY-MM')
        range = Moment(value).subtract(1, 'month').format('YYYY-M').split('-')
      } else {
        month = Moment(value).format('YYYY-MM')
        range = Moment(value).format('YYYY-M').split('-')
      }
      if (this.frequencyOfMonthlyData[month]) {
        this.monthlyData = this.frequencyOfMonthlyData[month]
        this.monthtags.push({ name: month, type: 'info' })
      } else {
        APIGetFrequencyOfMonthlyData({ shop: this.mallId, year: range[0], month: range[1] })
          .then((res) => {
            this.monthlyData = res.data.stats
            this.frequencyOfMonthlyData[month] = res.data.stats
            this.monthtags.push({ name: month, type: 'info' })
          })
      }
      const startOfCurrweek = Moment().subtract(Number(Moment().format('E')) - 1, 'day').format('YYYY-MM-DD')
      const chooseWeek = Moment(value).format('YYYY-MM-DD')
      let [ weekOfday, startOfWeek, startOfWeek1, endOfWeek, endOfWeek1, weekRange ] = []
      if (Moment(chooseWeek).isBefore(startOfCurrweek)) {
        weekOfday = Number(Moment(value).format('E'))
        startOfWeek = Moment(value).subtract(weekOfday - 1, 'day').format('YYYY-MM-DD')
        startOfWeek1 = Moment(value).subtract(weekOfday - 1, 'day').format('YYYY.MM.DD')
        endOfWeek = Moment(value).add(7 - weekOfday, 'day').format('YYYY-MM-DD')
        endOfWeek1 = Moment(value).add(7 - weekOfday, 'day').format('YYYY.MM.DD')
        weekRange = `${startOfWeek1}-${endOfWeek1}`
      } else {
        weekOfday = Number(Moment(value).format('E'))
        startOfWeek = Moment(value).subtract(weekOfday + 6, 'day').format('YYYY-MM-DD')
        startOfWeek1 = Moment(value).subtract(weekOfday + 6, 'day').format('YYYY.MM.DD')
        endOfWeek = Moment(value).subtract(weekOfday, 'day').format('YYYY-MM-DD')
        endOfWeek1 = Moment(value).subtract(weekOfday, 'day').format('YYYY.MM.DD')
        weekRange = `${startOfWeek1}-${endOfWeek1}`
      }
      APIGetFrequencyOfWeeklyData({ shop: this.mallId, startDate: startOfWeek, endDate: endOfWeek })
        .then((res) => {
          this.weeklyData = res.data.stats
          this.frequencyOfWeeklyData[weekRange] = res.data.stats
          this.weektags.push({ name: weekRange, type: 'info' })
        })
    },
    changeDay (value) {
      let dayarray = this.daytags.map(item => item.name)
      if (!(dayarray.includes(value)) && !this.frequencyOfDailyData.hasOwnProperty('value')) {
        APIGetFrequencyOfDailyData({ shop: this.mallId, date: value })
          .then((res) => {
            this.frequencyOfDailyData[value] = res.data.stats
            this.daytags.push({ name: value, type: 'info' })
          })
      }
    },
    handleCloseOfDay (tag) {
      this.daytags.splice(this.daytags.indexOf(tag), 1)
      if (this.daytags.length === 0) {
        this.daytags.push({ name: Moment().subtract(1, 'day').format('YYYY-MM-DD'), type: 'info' })
      }
    },
    changeWeek (value) {
      let weekOfday = Number(Moment(value).format('E'))
      let startOfWeek = Moment(value).subtract(weekOfday - 1, 'day').format('YYYY-MM-DD')
      let startOfWeek1 = Moment(value).subtract(weekOfday - 1, 'day').format('YYYY.MM.DD')
      let endOfWeek = Moment(value).add(7 - weekOfday, 'day').format('YYYY-MM-DD')
      let endOfWeek1 = Moment(value).add(7 - weekOfday, 'day').format('YYYY.MM.DD')
      let range = `${startOfWeek1}-${endOfWeek1}`
      let weekarray = this.weektags.map(item => item.name)
      if (!(weekarray.includes(range)) && !this.frequencyOfWeeklyData.hasOwnProperty('range')) {
        APIGetFrequencyOfWeeklyData({ shop: this.mallId, startDate: startOfWeek, endDate: endOfWeek })
          .then((res) => {
            this.frequencyOfWeeklyData[range] = res.data.stats
            this.weektags.push({ name: range, type: 'info' })
          })
      }
    },
    handleCloseOfWeek (tag) {
      this.weektags.splice(this.weektags.indexOf(tag), 1)
      if (this.weektags.length === 0) {
        this.weektags.push({
          name: Moment().subtract(Number(Moment().format('E')) + 6, 'day').format('YYYY.MM.DD') + '-' + Moment().subtract(Number(Moment().format('E')), 'day').format('YYYY.MM.DD'),
          type: 'info' }
        )
      }
    },
    changeMonth (value) {
      let month = Moment(value).format('YYYY-MM')
      let montharray = this.monthtags.map(item => item.name)
      if (!(montharray.includes(month)) && !this.frequencyOfMonthlyData.hasOwnProperty('month')) {
        let range = Moment(month).format('YYYY-M').split('-')
        APIGetFrequencyOfMonthlyData({ shop: this.mallId, year: range[0], month: range[1] })
          .then((res) => {
            this.frequencyOfMonthlyData[month] = res.data.stats
            this.monthtags.push({ name: month, type: 'info' })
          })
      }
    },
    handleCloseOfMonth (tag) {
      this.monthtags.splice(this.monthtags.indexOf(tag), 1)
      if (this.monthtags.length === 0) {
        this.monthtags.push({ name: Moment().subtract(1, 'month').format('YYYY-MM'), type: 'info' })
      }
    },
    showTable (ref) {
      switch (ref) {
        case 'Day':
          this.showDayTable = !this.showDayTable
          if (this.showDayTable) {
            this.$refs[ref].style.height = this.heightOfDayTable + 'px'
            this.$refs[ref].style.transition = 'height 0.8s ease'
          } else {
            this.$refs[ref].style.height = '0px'
            this.$refs[ref].style.transition = 'height 0.8s ease'
          }
          break
        case 'Week':
          this.showWeekTable = !this.showWeekTable
          if (this.showWeekTable) {
            this.$refs[ref].style.height = this.heightOfWeekTable + 'px'
            this.$refs[ref].style.transition = 'height 0.8s ease'
          } else {
            this.$refs[ref].style.height = '0px'
            this.$refs[ref].style.transition = 'height 0.8s ease'
          }
          break
        case 'Month':
          this.showMonthTable = !this.showMonthTable
          if (this.showMonthTable) {
            this.$refs[ref].style.height = this.heightOfMonthTable + 'px'
            this.$refs[ref].style.transition = 'height 0.8s ease'
          } else {
            this.$refs[ref].style.height = '0px'
            this.$refs[ref].style.transition = 'height 0.8s ease'
          }
          break
      }
    },
    // 下载表格
    SaveDateToDesktop (value) {
      switch (value) {
        case 'day':
          window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/enter-shop-frequency-daily/export?api_token=${this.token}&date=${this.mainDate}`
          break
        case 'week':
          const startOfCurrweek = Moment().subtract(Number(Moment().format('E')) - 1, 'day').format('YYYY-MM-DD')
          const chooseWeek = Moment(this.mainDate).format('YYYY-MM-DD')
          let [ weekOfday, startOfWeek, endOfWeek ] = ['', '', '']
          if (Moment(chooseWeek).isBefore(startOfCurrweek)) {
            weekOfday = Number(Moment(this.mainDate).format('E'))
            startOfWeek = Moment(this.mainDate).subtract(weekOfday - 1, 'day').format('YYYY-MM-DD')
            endOfWeek = Moment(this.mainDate).add(7 - weekOfday, 'day').format('YYYY-MM-DD')
          } else {
            weekOfday = Number(Moment(this.mainDate).format('E'))
            startOfWeek = Moment(this.mainDate).subtract(weekOfday + 6, 'day').format('YYYY-MM-DD')
            endOfWeek = Moment(this.mainDate).subtract(weekOfday, 'day').format('YYYY-MM-DD')
          }
          window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/enter-shop-frequency-weekly/export?api_token=${this.token}&start_date=${startOfWeek}&end_date=${endOfWeek}`
          break
        case 'month':
          let m = Moment().format('YYYY-MM') === Moment(this.mainDate).format('YYYY-MM')
            ? Moment(this.mainDate).subtract(1, 'month').format('YYYY-M').split('-')
            : Moment(this.mainDate).format('YYYY-M').split('-')
          window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/enter-shop-frequency-monthly/export?api_token=${this.token}&year=${m[0]}&month=${m[1]}`
          break
      }
    },
    // 设置日逛店次数分布  option
    setDayChartsOption (values) {
      // customerNumberEchartOption
      let xAxisarray = values.map(item => item.times)
      let option = Object.assign({}, customerNumberEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisarray })
      const base = {
        type: 'bar',
        barMaxWidth: '20%',
        name: Moment().subtract(1, 'day').format('YYYY-MM-DD')
      }
      option.series = [Object.assign({}, base, { data: values.map(item => Number(item.ratio.split('%')[0]).toFixed(2)) })]
      this.timesOfDailyChartsOption = option
    },
    // 设置周逛店次数分布  option
    setWeekChartsOption (values) {
      // customerNumberEchartOption
      // console.log('values:', values)
      let xAxisarray = values.map(item => item.times)
      let option = Object.assign({}, customerNumberEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisarray })
      const base = {
        type: 'bar',
        barMaxWidth: '20%',
        name: Moment().subtract(Number(Moment().format('E')) + 6, 'day').format('YYYY.MM.DD') + '-' + Moment().subtract(Number(Moment().format('E')), 'day').format('YYYY.MM.DD')
      }
      option.series = [Object.assign({}, base, { data: values.map(item => Number(item.ratio.split('%')[0]).toFixed(2)) })]
      this.timesOfWeeklyChartsOption = option
      // console.log('option:', option)
    },
    // 设置月逛店次数分布  option
    setMonthChartsOption (values) {
      let xAxisarray = values.map(item => item.times)
      let option = Object.assign({}, customerNumberEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisarray })
      const base = {
        type: 'bar',
        barMaxWidth: '20%',
        name: Moment().subtract(1, 'month').format('YYYY-MM')
      }
      option.series = [Object.assign({}, base, { data: values.map(item => Number(item.ratio.split('%')[0]).toFixed(2)) })]
      this.timesOfMonthlyChartsOption = option
    },
    // 逛店次数排序
    sortPercentConvMethods (a, b) {
      const prev = Number.parseFloat((a.goShoppingTines).substring(0, a.goShoppingTines.indexOf('次')))
      const curr = Number.parseFloat((b.goShoppingTines).substring(0, b.goShoppingTines.indexOf('次')))
      if (prev < curr) {
        return -1
      } else if (prev > curr) {
        return 1
      } else {
        return 0
      }
    },
    // api ======================================================
    APIGetFrequencyOfDailyData (date) {
      APIGetFrequencyOfDailyData({ shop: this.mallId, date: date })
        .then((res) => {
          this.dailydata = res.data.stats
          this.frequencyOfDailyData[date] = res.data.stats
          this.setDayChartsOption(res.data.stats)
        })
    },

    APIGetFrequencyOfWeeklyData (date) {
      let weekOfday = Number(Moment(date).format('E'))
      let startOfWeek = Moment(date).subtract(weekOfday + 6, 'day').format('YYYY-MM-DD')
      let startOfWeek1 = Moment(date).subtract(weekOfday + 6, 'day').format('YYYY.MM.DD')
      let endOfWeek = Moment(date).subtract(weekOfday, 'day').format('YYYY-MM-DD')
      let endOfWeek1 = Moment(date).subtract(weekOfday, 'day').format('YYYY.MM.DD')
      let range = `${startOfWeek1}-${endOfWeek1}`
      APIGetFrequencyOfWeeklyData({ shop: this.mallId, startDate: startOfWeek, endDate: endOfWeek })
        .then((res) => {
          this.weeklyData = res.data.stats
          this.frequencyOfWeeklyData[range] = res.data.stats
          this.setWeekChartsOption(res.data.stats)
        })
    },

    APIGetFrequencyOfMonthlyData (date) {
      let month = Moment(date).subtract(1, 'month').format('YYYY-MM')
      let range = Moment(date).subtract(1, 'month').format('YYYY-M').split('-')
      APIGetFrequencyOfMonthlyData({ shop: this.mallId, year: range[0], month: range[1] })
        .then((res) => {
          this.monthlyData = res.data.stats
          this.frequencyOfMonthlyData[month] = res.data.stats
          this.setMonthChartsOption(res.data.stats)
        })
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
  // scoped
  .shopTimes {
    .shopTimes-wrapper {
      position: relative;
      width: 100%;
      height: auto;
      .store-summary {
        width: 100%;
        height: auto;
        box-sizing: border-box;
        background-color: #FFF;
        padding: 10px 20px;
        box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2);
        .summary-title {
          padding: 10px 0;
          height: 30px;
          line-height: 30px;
          border-bottom: 1px solid #DFDFDF;
          overflow: hidden;
          .name {
            .pageName{
              font-weight: bold;
              font-size: 18px;
            }
            .instructions {
            color: #777;
           }
          }
          .date {
            float: left;
            margin-left: 30px;
            color: #777;
            font-size: 14px;
          }
        }
        .summary-main {
          margin-top: 10px;
          padding: 10px;
        }
      }
      .box{
        background-color: #FFF;
        box-sizing: border-box;
        box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2);
        padding: 20px 20px;
        background-color: #FFF;
        margin-top: 20px;
        }
      .charts{
        margin-top: 20px;
        position: relative;
        .charts-title{
          margin-bottom: 10px;
          height: 30px;
          line-height: 30px;
          text-align: center;
        }
        .dayPicker{
          position: absolute;
          right: 0;
          top: 0;
        }
        .panel-charts{
          padding: 20px 0;
          width: 100%;
          height: 350px;
        }
      }
      .table{
        margin-top: 10px;
        .trigger{
          color: #1AAD19;
          font-size: 14px;
        }
      }
      .tableWrapper{
        .tablelist{
          .panel-title {
            font-size: 16px;
            margin-bottom: 10px;
            .instructions {
              color: #777;
            }
            .save-csv-link {
              float: right;
              cursor: pointer;
              font-size: 13px;
              color: #0269c8;
            }
          }
        }
      }
    }
    .compass-tabs {
      box-sizing: border-box;
      margin-top: 20px;
      padding: 10px 20px;
      width: 100;
      background-color: #FFF;
      .data-view {
        .panel-title {
          font-size: 16px;
          .instructions {
            color: #777;
          }
          .save-csv-link {
            float: right;
            cursor: pointer;
            font-size: 13px;
            color: #0269c8;
          }
        }
        .panel-charts {
          padding: 20px 0;
          width: 100%;
          height: 350px;
        }
        .panel-table {
          padding: 20px 0;
          width: 100%;
        }
      }
    }
  }
</style>
